<template>
  <div class="login-container">
  <!-- 顶部导航栏 -->
  <van-nav-bar
    class="app-nav-bar"
    title="登录"
    left-arrow
    @click-left="$router.back()"
  />
    <!-- 登录表单 -->
    <van-form
      :show-error="false"
      :show-error-message="false"
      validate-first
      ref="login-form"
      @submit="onLogin"
      @failed="onFailed"
      >
        <van-field
        v-model="user.mobile"
        icon-prefix="toutiao"
        left-icon="shouji"
        placeholder="请输入手机号"
        name="mobile"
        center
        :rules="formRules.mobile"
        />
        <van-field
          v-model="user.code"
          icon-prefix="toutiao"
          left-icon="yanzhengma"
          placeholder="请输入验证码"
          name="code"
          center
          :rules="formRules.code"
        >
          <template #button>
            <van-count-down
              v-if="isCountDownShow"
              :time="1000 * 60"
              format="ss s"
              @finish="isCountDownShow=false"
             />
            <van-button
            v-else
            class="sen-btn"
            size="small"
            round
            :loading="isSendSmsLoading"
            @click.prevent="onSendSms"
            >发送验证码</van-button>
          </template>
        </van-field>
        <div class="login-btn-wrap">
          <van-button class="login-btn" type="info" block >登录</van-button>
        </div>
    </van-form>
  </div>
</template>

<script>
import { login, sendSms } from '@/api/user'
// import { Toast } from 'vant'

export default {
  name: 'LoginIndex',
  data () {
    return {
      user: {
        mobile: '13922222222',
        code: '246810'
      },
      formRules: {
        mobile: [
          { required: true, message: '请输入手机号' },
          { pattern: /^1(3|5|7|8|9)\d{9}$/, message: '手机号码格式错误' }
        ],
        code: [
          { required: true, message: '请输入验证码' },
          { pattern: /^\d{6}$/, message: '验证码格式错误' }
        ]
      },
      isCountDownShow: false,
      isSendSmsLoading: false
    }
  },
  methods: {
    // 1. 找到数据接口
    // 2. 封装请求方法
    // 3. 请求调用登录
    async onLogin () {
      // Toast.loading({
      //   message: '登录中...',
      //   forbidClick: true,
      //   duration: 0
      // })
      this.$toast.loading({
        message: '登录中...',
        forbidClick: true,
        duration: 0
      })
      try {
        const { data } = await login(this.user)
        // 4. 处理响应结果
        this.$toast.success('登录成功')
        // 将后端返回的用户登录状态(token等数据)放到vuex
        this.$store.commit('setUser', data.data)
        // 清除layout缓存，重新渲染
        this.$store.commit('removeCachePage', 'LayoutIndex')
        // 跳转回原来的页面
        // this.$router.back()
        this.$router.push(this.$route.query.redirect || '/')
      } catch (err) {
        console.log(err)
        this.$toast.fail('登录失败,手机号或验证码错误')
      }
    },
    onFailed (error) {
      // console.log(error)
      if (error.errors[0]) {
        this.$toast({
          message: error.errors[0].message,
          position: 'top'
        })
      }
    },
    async onSendSms () {
      try {
        // 校验手机号码
        await this.$refs['login-form'].validate('mobile')
        // 验证通过, 请求发送验证码
        this.isSendSmsLoading = true
        await sendSms(this.user.mobile)
        // 短信发出去了 显示倒计时
        this.isCountDownShow = true
      } catch (err) {
      // 校验手机号码
      // 验证通过 -> 请求发送验证码 -> 显示倒计时
      // 倒计时结束 -> 隐藏倒计时 -> 显示发送按钮
        let message = ''
        if (err && err.response && err.response.status === 429) {
          // 发送短信失败的错误信息提示
          message = '发送太频繁了，请稍后重试'
        } else if (err.name === 'mobile') {
          // 表单验证失败的错误提示
          message = err.message
        } else {
          message = '发送失败，请稍后重试'
        }
        this.$toast({
          message,
          position: 'top'
        })
      }
      this.isSendSmsLoading = false
    }
  }
}
</script>

<style lang="less" scoped>
.login-container{
  .send-btn {
    width: 76px;
    height: 23px;
    background-color: #ededed;
    .van-button__text {
      font-size: 11px;
      color: #666;
    }
  }
  .login-btn-wrap {
    padding: 26px 16px;
    .login-btn {
      background-color: #6db4fb;
      border: none;
      .van-button__text{
        font-size: 15px;
      }
    }
  }
}
</style>
